package com.framework.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.framework.dao.GoodsBannerDao;
import com.framework.entity.ter.TerGoodsBanner;
import com.framework.exception.RRException;
import com.framework.page.PageUtils;
import com.framework.service.GoodsBannerService;
import com.framework.utils.string.StringUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 商品轮播服务层
 * @author wq
 */
@Service("goodsBannerService")
public class GoodsBannerServiceImpl extends ServiceImpl<GoodsBannerDao, TerGoodsBanner> implements GoodsBannerService {


    @Override
    public List<TerGoodsBanner> queryGoodsBannerList(Long goodsId) {
        if (goodsId == null || goodsId == 0) {
            throw new RRException("9000", "goodsId不能为空");
        }
        return baseMapper.queryGoodsBannerList(goodsId);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insertBannersList(String[] bannerUrls, String goodsId) {
        //获取当前图片最大播放顺序
        Integer sort = this.baseMapper.queryMaxSort(Long.valueOf(goodsId));

        TerGoodsBanner terGoodsBanner;
        if(sort==null){
            sort=0;
        }
        for (int i = 0; i < bannerUrls.length; i++) {
            terGoodsBanner = new TerGoodsBanner();
            terGoodsBanner.setBannerImg(bannerUrls[i]);
            terGoodsBanner.setGoodsId(Long.valueOf(goodsId));
            terGoodsBanner.setCreateTime(new Date());
            terGoodsBanner.setSort(sort + i+1);
            this.baseMapper.insert(terGoodsBanner);
        }
    }

    @Override
    public PageUtils queryBannerListByGoodsId(Map<String, Object> params) {
        Integer pageSize= Integer.valueOf(params.get("limit").toString());
        Integer currPage= Integer.valueOf(params.get("page").toString());
        params.put("start",(currPage-1)*pageSize);
        params.put("limit",pageSize);
        List<TerGoodsBanner> list=baseMapper.queryBannerListByGoodsId(params);
        Integer totalCount=baseMapper.queryBannerCountByGoodsId(params);
        return new PageUtils(list,totalCount,pageSize,currPage);
    }

    @Override
    public Integer updateBanner(Long goodsBannerId, String bannerUrl, Integer sort) {
       TerGoodsBanner terGoodsBanner=this.baseMapper.selectById(goodsBannerId);
        if(!StringUtil.isEmpty(bannerUrl)){
            terGoodsBanner.setBannerImg(bannerUrl);
        }
       terGoodsBanner.setSort(sort);
        Integer count = this.baseMapper.updateById(terGoodsBanner);
        return count;
    }
}
